 var table ,form ,laypage ,layer ,element ,laydate ,upload;//时间组件
var check=true;
$(function(){ 
	var hid=getQueryString("id");
	var saveurl="/equipment/saveEquipment.do";
	layui.use(['table','form','laypage','layer', 'element', 'laydate','upload'], function(){
		 table = layui.table;
		 form=layui.form;
		 laypage = layui.laypage ;//分页
		 layer = layui.layer ;//弹层
		 element = layui.element; //元素操作
		 laydate = layui.laydate; //时间组件 
		 upload = layui.upload;
         TimeTools();//时间
         dictPublicfun();
         //生产厂家
     	$.ajax({
     		url:'/supplier/getList.do',
     		type:'POST',
     		asyn:false,
     		//data:{"request":JSON.stringify({"groupId":type})},
     		timeout: 200000,
     		headers: setHeader(),
     		success:function(data){
     			//获得服务器响应
     			$("#supplierId option").not(":eq(0)").remove();//清空
     			form.render();  
     			var res = data.resultData.data;	
     			if(data.status == 200) {
     				if(res.length>0){
     					$.each(res, function(i,json){
     	                   $("#supplierId").append($("<option itemid='" + json["id"] + "' value='" + json["id"] + "'>" + json["name"] + "</option>"));
     	                   form.render();  
     					});
     				}
                      
     			}else if(data.status == 666){
     				 TIMEOUT(); 
     		    }
     		}		
     	})
     	//保养周期选择
     	form.on('select(typeFilter)', function(data){
				if(data.value == ""){
					$(".MaintainDate").html("");
					form.render();  
				}else{
					$.ajax({
			     		url:'/equipment/getMaintainDate.do',
			     		type:'POST',
			     		asyn:false,
			     		data:formatParam({"cycle":data.value,"equipmentId":$("#id").val()}),
			     		timeout: 200000,
			     		headers: setHeader(),
			     		success:function(data){
			     			if(data.status == 200) {
			     				$(".MaintainDate").html("设备下次保养时间："+changeTime(data.resultData));
			     				form.render();
			                      
			     			}else if(data.status == 666){
			     				 TIMEOUT(); 
			     		    }
			     		}		
			     	})
				}
		});
         //设备类型
 		//上级菜单选择
 		var setting = {
 			view: {
 				dblClickExpand: false
 			},
 			data: {
 				simpleData: {
 					enable: true,
 					idKey : "id",
 					pIdKey: "pid"
 				},
 				key: {
 					url:'none'
 				}
 			},
 			callback: {
 				onClick: onClick,
 				onAsyncSuccess: function(event, treeId, treeNode, msg) {
 				    $.fn.zTree.getZTreeObj(treeId).expandAll(true);//异步加载完成后展开tree
 				}
 			}
 		};
 		$.ajax({
 	        url: "/equipmentType/getList.do",               //请求地址
 	        type: "POST",              //请求类型
 	        data:{},              //请求数据
 	        timeout: 200000,                //请求超时时间(毫秒)
 	        headers: setHeader(),
 	        success:function(res){         //请求成功
 	     	   if(res.status == 200){
 	     		  var zNodes=res.resultData.data
 	     		  var zTree = $.fn.zTree.init($("#treeDemo"), setting ,zNodes);
 	     		 zTree.expandAll(true);//节点展开
 			   }else if(res.status == 666){
 				   TIMEOUT(); 
 		       }else{
   					layer.msg(res.resultMsg, {icon: res.icon});
   				} 
 	       }
 	    })
     	//图片上传
         $("#addicon").change(function (ev) { 
         	var imgData;
         	// 构造一个文件渲染对象
 		    var reader = new FileReader();
 		    // 得到文件列表数组
 		    var fileObj = $(this)[0].files[0];
 		    // 拿到文件数据
 		    reader.readAsDataURL(fileObj);

 		    reader.onload = function() {
 		        // 获取文件信息
 		        imgData = reader.result;		    
 		    };
             var formData = new FormData();
             formData.append('myFile', $(this)[0].files[0]); // 固定格式
             var tishi = layer.open({
           	    title: false
                 ,closeBtn: 0
                 ,shadeClose: false
                 ,area: ['130px', '70px']
                 ,type: 1
                 ,content: '图片上传中...'
             }); 
             $.ajax({
                   url:'/equipment/uploadEquipment.do' ,//后台接收数据地址
                   headers: setHeader(),
                   data:formData,
                   type: "POST",
                   dataType: "json",
                   cache: false,			//上传文件无需缓存
                   processData: false,		//用于对data参数进行序列化处理 这里必须false
                   contentType: false,
                   success:function(res){
                   	if(res.status==200){
                   		$("#viewer_icon img").attr("src",imgData);//查看地址
 						$("#viewer_icon img").attr("data-original",imgData);//查看地址
                   		$("#icon").val(res.resultData.path);
                   		layer.msg("图片选择完成", {icon: 6});
                   		form.render();//需要渲染一下
                   	}else if(res.status == 666){
                   	  TIMEOUT(); 
                     }else{
                       	layer.msg(res.resultMsg, {icon: res.icon});                    		
                   	}
                   	layer.close(tishi);
                   }
               })
         });
     //附件列表示例
       var demoListView = $('#demoList'),
       uploadListIns = upload.render({
           elem: '#testList',
	         // ,url: 'https://httpbin.org/post' //改成您自己的上传接口
	         accept: 'file',
	         multiple: true,
	         auto: false,
	         bindAction: '#testListAction',
	         choose: function(obj){   
	            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
	            //读取本地文件            
	            obj.preview(function(index, file, result){               
	                var formData = new FormData();
	                formData.append('myFile',file); // 固定格式
	                var tishi = layer.open({
		                    title: false
		                    ,closeBtn: 0
		                    ,shadeClose: false
		                    ,area: ['130px', '70px']
		                    ,type: 1
		                    ,content: '附件上传中...'
	                }); 
	                $.ajax({
	                      url:'/equipment/uploadEquipment.do',//后台接收数据地址
	                      headers: setHeader(),
	                      data:formData,
	                      type: "POST",
	                      async:false,//请求类型
	                      dataType: "json",
	                      cache: false,   //上传文件无需缓存
	                      processData: false,  //用于对data参数进行序列化处理 这里必须false
	                      contentType: false,
	                      success:function(res){
	                       if(res.status==200){
	                    	   var tr = $(['<tr id="upload-'+ index +'">'
					   			                ,'<td><span class="filename">'+ file.name +'</span><input type="hidden" class="enclosure" value="'+res.resultData.path+'"></td>'
					   			                ,'<td>'       
					   			                   ,'<a href="javascript:; return false"  class="layui-btn layui-btn-xs layui-btn-danger demo-delete" filelistid="">删除</a>'
					   			                ,'</td>'
					   			              ,'</tr>'].join(''));
	                    	   //删除
	         	              tr.find('.demo-delete').on('click', function(){
//	         	                delete files[index]; //删除对应的文件
//	         	                tr.remove();
	         	            	 delectte(this,res.resultData.path)  
	         	                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
	         	              });              
	         	              demoListView.append(tr);
	                       }else{
	                           layer.msg(res.resultMsg, {icon: res.icon});
	                       } 
	                       layer.close(tishi); 
	                      },
	                      failure: function (res) {
	                        
	                      }
	                   })                                        	             
	            });
	          }
	          ,done: function(res, index, upload){
	        	  
	          }
	        });
       setTimeout(function () {
           if(hid){//编辑
         	   $("#Title").html("设备信息编辑");    	   
         	   saveurl="/equipment/editEquipment.do";
         	   var questData = {"id": hid};
          	  	$.ajax({
      	           url: "/equipment/getOneEquipment.do",               //请求地址
      	           type: "POST",              //请求类型
      	           data:formatParam(questData),              //请求数据
      	           timeout: 200000,                //请求超时时间(毫秒)
      	           headers: setHeader(),
      	           success:function(res){         //请求成功
      	        	   if(res.status == 200)
      	  				{
      	        		   	var num=res.resultData;
      	        		    var fileList=res.resultData.listFile;
      	        		    $("#id").val(hid);
      	        		    $("#createTime").val(num.createTime);
      	    				$("#name").val(num.name); 	    				  	    				
      	    				$("#code").val(num.code); 
      	    				$("#icon").val(num.image);
      	    				$("#qrcode").val(num.qrcode);
      	    				$("#pid").val(num.type);
      	    				$("#pname").val(num.typeZh);
      	    				$("#state").val(num.state); 	    				  	    				
      	    				$("#model").val(num.model); 
      	    				$("#nfc").val(num.nfc);
      	    				$("#supplierId").val(num.supplierId);
      	    				$("#startTime").val(changeTime(num.productionTime));
      	    				$("#endTime").val(changeTime(num.putTime));
      	    				$("#position").val(num.position);
      	    				$("#cycle").val(num.cycle);
      	    				$("#grade").val(num.grade);
      	    				$(".MaintainDate").html("设备下次保养时间："+changeTime(num.endTime));
      	    				$("#stationName").val(num.stationName); 
     	        		    $("#station").val(num.station);
      	    				if(num.imageZh){
    			  		    	$("#viewer_icon").find("img").attr({"src":num.imageZh,"data-original":num.imageZh});//查看地址
    			  		    	$("#icon").val(num.image)
    			  		    }	
      	    				if(fileList.length>0){
                            	for(var m=0;m<fileList.length;m++){
                            		 var filetype='';
    	                       		 var filebtn='';
    	                       		 if(fileList[m].type==1){//图片
    	                       			 filetype='<div id="'+fileList[m].id+'" onclick="Viewerfun(\''+fileList[m].id+'\')" class="table_img">'+
    				  	                  	           '<img data-original="'+fileList[m].addressZh+'" src="'+fileList[m].addressZh+'"  alt="图片"  style="width:30px;height:30px" />'+
    				  	                  	           '<span class="">'+ fileList[m].name +'</span>'+
    				  	  	                  	  '</div>'
    	                       		 }else if(fileList[m].type==5){//视频
    	                       			 filetype='<a href="javascript:; return false"  class="layui-btn layui-btn-xs" title="视频播放" onclick="videoclick(\''+fileList[m].addressZh+'\')">'+fileList[m].name+'</a>';
    	                       		 }else{
    	                       			 filetype='<a title="文档下载" class="layui-btn layui-btn-xs layui-btn-normal" href="/equipment/download.do?filePath='+fileList[m].address+'" download="文件下载">'+fileList[m].name+'</a>';
    	                       		 } 
                            		 var tr = $(['<tr id="upload-'+ fileList[m].id +'">'
                            			 	,'<td>'
                            			 	    ,filetype
                            			 	   //,'<span class="filename">'+ fileList[m].addressZh +'</span>'
                            			 	   ,'<input type="hidden" class="" value="'+fileList[m].address+'"></td>'
    			   			                ,'<td>' 
    			   			                   ,'<a href="javascript:; return false"  class="layui-btn layui-btn-xs layui-btn-danger" filelistid="'+ fileList[m].id +'" onclick="delectte(this,\''+fileList[m].address+'\')">删除</a>'
    			   			                ,'</td>'
    			   			              ,'</tr>'].join(''));			             	              
    				  	            $('#demoList').append(tr);
                            	}
                            }
    	    				$("#remarks").val(num.remarks);
      	    				form.render();
      	  				}else{          	  				    
      	  					layer.msg(res.resultMsg, {icon: res.icon});
      	  				}
      	  				      
                    }
                 })
            }
       }, 1000); 
    	 //表单验证
        form.verify({	  
        	fname: function(value, item)
	          { 
	  			  if(validate.isBlank(value))
	  			  {
	  				 return "请填写设备名称";
	  			  }
	  			 if(!validate.isLength(value,1,50))
  		      {
  		         return '设备名称长度不能超过50个字符';
  		      }
	  	  },
	  	  fcode: function(value, item)
          { 
  			  if(validate.isBlank(value))
  			  {
  				 return "请填写设备编码";
  			  }
  			 if(!validate.isLength(value,1,50))
		      {
		         return '设备编码长度不能超过50个字符';
		      }
  	      },
          ftype: function(value, item)
           {   //作业状态验证
				  if(validate.isBlank(value))
				  {
					 return "请选择设备类型";
				  }
          },
          fstate: function(value, item)
          {   //作业状态验证
				  if(validate.isBlank(value))
				  {
					 return "请选择设备状态";
				  }
          },
          fgrade: function(value, item)
          {   //作业状态验证
				  if(validate.isBlank(value))
				  {
					 return "请选择设备电压等级";
				  }
         },
          fqrcode: function(value, item)
          {  
			  if(validate.isBlank(value))
			  {
				 return "请填写设备二维码";
			  }
			  if(!validate.isLength(value,1,50))
		      {
		         return '设备规格二维码长度不能超过50个字符';
		      }
          },
          fmodel: function(value, item)
          {  
			  if(validate.isBlank(value))
			  {
				 return "请填写设备规格型号";
			  }
			  if(!validate.isLength(value,1,50))
		      {
		         return '设备规格型号长度不能超过50个字符';
		      }
          },
          fnfc: function(value, item)
          {  
			  if(!validate.isLength(value,1,50))
		      {
		         return '设备nfc编码长度不能超过50个字符';
		      }
          },
          fsupplierId:function(value, item)
	          { 
		         if(validate.isBlank(value))
			         {
			         	return "请选择生产厂家";
			       }
	    }, 
		 fproductionTime:function(value, item)
         { 
	         if(validate.isBlank(value))
		         {
		         	return "请选择投产时间";
		       }
	     },
	     fstation: function(value, item)
	        {  
			  if(validate.isBlank(value))
			  {
				 return "请选择所属变电站";
			  }
	     },
		fcycle: function(value, item)
         {  
			  if(validate.isBlank(value))
			  {
				 return "请选择保养周期";
			  }
	     },
	    fsolutions: function(value, item)
        {   //处理结果验证
			  if(validate.isBlank(value))
			  {
				 return "请填写处理结果";
			  }
			 if(!validate.isLength(value,1,200))
		      {
		         return '处理结果长度不能超过200个字符';
		      }
	      },
         fremarks: function(value, item)
	          {   //备注长度验证
	  			 if(!validate.isLength(value,0,200))
  		      {
  		         return '备注长度不能超过200个字符';
  		      }
	  	   }
		  	          
       })
      form.on('submit(formDemo)', function(data){  
			this.blur();//防止点回车，按钮重复点击
			var loadIndex = layer.load(1);//显示加载层
			//判断时间为空值为null
			var requestData= formToJsonObj("form_edit", []);
    		var fileList=[];//会议文件
    		var filesmore=$("#demoList").find("tr");
            if(filesmore){
            	$("#demoList").find("tr").each(function(){
            		if($(this).find(".enclosure").length>0){
            			fileList.push({"name":$(this).find(".filename").html(),"address":$(this).find(".enclosure").val()})
            		}else{
            			fileList=[]
            		}           		
            	})
            } 
            requestData.listFile=fileList;
			$.ajax({
				url:saveurl,
				type:'POST',
				async:false,
				data:formatParam(requestData),
				timeout: 200000,
				headers: setHeader(),
				success:function(res){         //请求成功
		        	   if(res.status == 200) {  
		        		   layer.msg(res.resultMsg, {icon: res.icon},function(){
		   					     var index = parent.layer.getFrameIndex(window.name);
		   					      parent.layui.table.reload("tabledata")//
		   					      parent.layer.close(index);//关闭弹出的子页面窗口
		   					}); 					
		        	    }else if(res.status == 666){
		  					TIMEOUT(); 
		  		        }else{
		  					layer.msg(res.resultMsg, {icon: res.icon});		  					
		  				}  
		        	   layer.close(loadIndex);//关闭加载层
	              }		
			})
		  return false; //阻止表单跳转。
	  })
   }) 	
})
//附件图片点击事件
function Viewerfun(id){	
	var viewer = new Viewer(document.getElementById(id), {
		url: 'data-original',
		navbar: false
  });
}
//视屏点击查看
function videoclick(viderZh) {
	//视频播放
	$("body").find("#my-video").remove();
   var $content='<video id="my-video" class="video-js vjs-big-play-centered vjs-fluid" controls preload="auto" poster="" style="width:100%;height:100%" data-setup="{}">'+
          '<source src="'+viderZh+'" type="video/mp4">'+
          '<source src="'+viderZh+'" type="video/webm">'+
          '<source src="'+viderZh+'" type="video/ogg">'+
       '</video>';
   	layer.open({
            type: 1,
            area: ['800px', '500px'],
            fix: false, //不固定
            maxmin: true,
            shadeClose: true,
            tipsMore: true,
            shade:0.4, //遮罩层
            title: ['视频播放','background:#1E9FFF;color:#fff'],
            content:$content
        }); 
     //设置中文
     videojs.addLanguage('zh-CN', {
      "Play": "播放",
      "Pause": "暂停",
      "Current Time": "当前时间",
      "Duration": "时长",
      "Remaining Time": "剩余时间",
      "Progress": "进度",
      "Fullscreen": "全屏",
      "Non-Fullscreen": "退出全屏",
      "Close": "关闭",
      "Video Player": "视频播放器",
      "Replay": "重播",
      "Progress Bar": "进度小节",
      "Volume Level": "音量"
    });
   var myPlayer = videojs('my-video', { fluid: true }, function () {
  	});
}
function delectte(Tr,address){
	Tr.blur();//防止点回车，按钮重复点击
	  //删除
	var ID=$(Tr).attr("filelistid");
    layer.confirm('真的要删除这行数据？', function () {
    	var requestData={"id":ID,
				"address":address
    	}
	 $.ajax({
			url:'/equipment/deleteEquipmentFile.do',
			type:'POST',
			async:false,
			//data:{"id":id,"address":address},
			data:formatParam(requestData),
			timeout: 200000,
			headers: setHeader(),
			success:function(res){         //请求成功
	        	   if(res.status == 200)
	        	   {	 $(Tr).parents("tr").remove();
						layer.msg(res.resultMsg, {icon: res.icon});	
	    	   		}else if(res.status == 666){
	  					TIMEOUT(); 
	  		        }else{
	  					layer.msg(res.resultMsg, {icon: res.icon});
	  				} 
	        	   return false
	          }		
		})
    });	
}
function onClick(e, treeId, treeNode) {
	$("#pname").val(treeNode.name);
	$("#pid").val(treeNode.id);
	hideMenu();
}
function showMenu() {
var cityObj = $("#pname");
var cityOffset = $("#pname").offset();
$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
$('ul.ztree').width(cityObj.width());//设置下拉菜单宽度	
$("body").bind("mousedown", onBodyDown);
}
function hideMenu() {
$("#menuContent").fadeOut("fast");
$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
hideMenu();
}
}